package com.cnebula.common.hadoop.oozie.client.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;

//@EasyService(beanFactory=Object.class)
public class OozieHttpClient {

	Gson gson;

	List<Integer> okStatus = new ArrayList<Integer>();

	public OozieHttpClient() {
		gson = new GsonBuilder().disableHtmlEscaping().create();

		okStatus.add(200);
		okStatus.add(201);
	}
	
	public List<Integer> getOkStatus(){
		return okStatus;
	}

	public String execute(HttpUriRequest request) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		JsonObject rst = new JsonObject();
		try {
			CloseableHttpResponse response = httpclient.execute(request);
			try {
				StatusLine statusline = response.getStatusLine();
				Header[] headers = response.getAllHeaders();
				Map<String, String> map = new HashMap<String, String>();
				for (int i = 0; i < headers.length; i++) {
					Header header = headers[i];
					map.put(header.getName(), header.getValue());
				}
				rst.add("HttpStatus", gson.toJsonTree(statusline));
				rst.add("HttpHeader", gson.toJsonTree(map));

				int code = statusline.getStatusCode();
				if (okStatus.contains(code)) {
					// 获取响应实体
					HttpEntity entity = response.getEntity();
					Object object = gson.fromJson(EntityUtils.toString(entity, "UTF-8"), Object.class);
					rst.add("Response", gson.toJsonTree(object));
				}
			} finally {
				response.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return rst.toString();
	}

	public String get(String url) {
		HttpGet httpget = new HttpGet(url);
		httpget.addHeader("Content-Type", "application/xml");
		httpget.addHeader("charset", "UTF-8");

		return this.execute(httpget);
	}

	public String post(String url, String data) {
		HttpPost httppost = new HttpPost(url);
		httppost.addHeader("Content-Type", "application/xml");
		httppost.addHeader("charset", "UTF-8");

		StringEntity dataEntity = new StringEntity(data, "UTF-8");
		httppost.setEntity(dataEntity);

		return this.execute(httppost);
	}
}
